# coding:utf-8

# Create your views here.
from django.db import models
from auth.models import Token
from django.contrib.auth.models import User
from signing.models import SaleMan
from signing.models import Brand
from django.core import serializers
from django.views.decorators.csrf import csrf_exempt
import json
from django.http import HttpResponse
from auth.utils import json_response, token_required
from signing.models import Order
from signing.models import Status
from signing.models import Property
from signing.models import Client
import datetime
from signing.models import Item
from django.forms.models import model_to_dict
import os
# 分页器
from  django.core.paginator import Paginator

# 预约
@csrf_exempt
@token_required
def add(request):
    if request.method == 'POST':

        dic =  request.REQUEST
        client = Client()
        # print dic[u'category']
        if u'联系人' not in dic:
            return json_response({'state':'failed',
                                  'message':'error client name'})
        if u'电话' not  in dic:
            return json_response({'state':'failed',
                                  'message':'error client phone'})
        if u'邮箱' not in dic:
            return json_response({'state':'failed',
                                  'message':'error client email'})
        if u'色调' not in dic:
            return json_response({'state':'failed',
                                  'message':'error hue'})
        if u'主题' not in dic or dic[u'主题'] is None:
            return json_response({'state':'failed',
                                  'message':'error client theme'})
        if u'预付款' not in dic or not dic[u'预付款'].isdigit() :
            return json_response({'state':'failed',
                                  'message':'error prepay'})
        if u'付款方式' not in dic:
            return json_response({'state':'failed',
                                  'message':'error pay style'})
        if u'负责人' not in dic:
            return json_response({'state':'failed',
                                  'message':'error saleman'})
        clientarray = Client.objects.filter(name=dic[u'联系人'],phone=dic[u'电话'])

        if len(clientarray):
            client = clientarray[0]
        else:
            client = Client(name=dic[u'联系人'], phone=dic[u'电话'])
        client.save()
        # print client
        today = datetime.datetime.now().strftime("%Y-%m-%d")
        todaystring = str(today)
        todaystring = "".join(todaystring.split('-'))

        advance_pay = int(dic[u'预付款'])

        saleman = dic[u'负责人'].split(" ")

        # print saleman
        jobnumber = jobNumber = saleman[1][len(saleman[1])-3:]

        # print jobnumber
        xiaoshou = SaleMan.objects.get(jobNumber=jobnumber)

        # print xiaoshou
        todayorder = Order.objects.filter(saleman=xiaoshou).filter(orderTime=today)

        number = len(todayorder)
        # print str(number)
        status = Status.objects.get(name=u'已预约')

        if dic[u'category'] == u'结婚':
            property = Property.objects.get(name=u'结婚')

            role1 = dic[u'新郎']
            role2 = dic[u'新娘']
            address = dic[u'结婚地址']
            weddingtime = dic[u'结婚时间']

            orderid = ""

            if number < 9:
                orderid = 'HL' + todaystring + jobnumber + '0' + str(number + 1)
            else:
                orderid = 'HL' + todaystring + jobnumber + str(number + 1)

            order = Order(orderID=orderid, status=status,weddingTime=weddingtime,weddingAddress=dic[u'结婚地址'],orderTime=today, party_nature=property, role1=role1,
                          role2=role2, client=client, saleman=xiaoshou, advancePay=advance_pay,hue = dic[u'色调'],theme=dic[u'主题'])
            order.save()

        if dic[u'category'] == u'回门':

            property = Property.objects.get(name=u'回门')
            role1 = dic[u'新郎']
            role2 = dic[u'新娘']
            address = dic[u'回门地址']
            weddingtime = dic[u'回门时间']
            orderid = ""

            if number < 9:
                orderid = 'HL' + todaystring + jobnumber + '0' + str(number + 1)
            else:
                orderid = 'HL' + todaystring + jobnumber + str(number + 1)
            # print orderid
            order = Order(orderID=orderid, answerDoorTime=weddingtime,answerDoorAddress=address,status=status, orderTime=today, party_nature=property, role1=role1,
                          role2=role2, client=client, saleman=xiaoshou, advancePay=advance_pay,hue = dic[u'色调'],theme=dic[u'主题'])
            order.save()

        if dic[u'category'] == u'合办':
            print 'xx'
            property = Property.objects.get(name=u'合办')
            role1 = dic[u'新郎']
            role2 = dic[u'新娘']
            backaddress = dic[u'回门地址']
            backtime = dic[u'回门时间']
            address = dic[u'结婚地址']
            weddingtime = dic[u'结婚时间']
            orderid = ""

            if number < 9:
                orderid = 'HL' + todaystring + jobnumber + '0' + str(number + 1)
            else:
                orderid = 'HL' + todaystring + jobnumber + str(number + 1)
            # print orderid
            order = Order(orderID=orderid, weddingAddress=address,weddingTime=weddingtime,answerDoorTime=backtime,answerDoorAddress=backaddress,status=status, orderTime=today, party_nature=property, role1=role1,
                          role2=role2, client=client, saleman=xiaoshou, advancePay=advance_pay,hue = dic[u'色调'],theme=dic[u'主题'])
            order.save()
        if dic['category'] == u'生日':

            property = Property.objects.get(name=u'生日')
            role1 = dic[u'寿星']

            address = dic[u'宴会地址']
            weddingtime = dic[u'宴会时间']
            orderid = ""

            if number < 9:
                orderid = 'SR' + todaystring + jobnumber + '0' + str(number + 1)
            else:
                orderid = 'SR' + todaystring + jobnumber + str(number + 1)
            # print orderid
            order = Order(orderID=orderid,weddingTime=weddingtime,weddingAddress=address,status=status, orderTime=today, party_nature=property, role1=role1, client=client, saleman=xiaoshou, advancePay=100)
            order.save()
        if dic[u'category'] == u'其他':

            property = Property.objects.get(name=u'其他')
            role1 = dic[u'主角']

            address = dic[u'宴会地址']
            weddingtime = dic[u'宴会时间']
            orderid = ""

            if number < 9:
                orderid = 'QT' + todaystring + jobnumber + '0' + str(number + 1)
            else:
                orderid = 'QT' + todaystring + jobnumber + str(number + 1)
            # print orderid
            order = Order(orderID=orderid,weddingTime=weddingtime,weddingAddress=address,status=status, orderTime=today, party_nature=property, role1=role1, client=client, saleman=xiaoshou, advancePay=advance_pay,hue = dic[u'色调'],theme=dic[u'主题'])
            order.save()
        return json_response({
            'status': 'success',
            'orderid':orderid
        })
    elif request.method == 'OPTIONS':
        return json_response({})
    else:
        return json_response({
                                 'error': 'Invalid Method'
                             }, status=405)

# 签约
@csrf_exempt
@token_required
def modify(request):

    if request.method == 'POST':
        dic =  request.REQUEST
        if  u'订单号' not in dic or dic[u'订单号'] is None:

            return json_response({'state':'failed','message':'lack of orderID'})
        if  u'品牌' not in dic  or dic[u'品牌'] is None:
            return json_response({'state':'failed','message':'lack of brand'})
        if  u'全款' not in dic  or dic[u'全款'] is None:
            return json_response({'state':'failed','message':'lack of allpay'})
        if  u'预付款' not in dic  or dic[u'预付款'] is None:
            return json_response({'state':'failed','message':'lack of prepay'})
        if  u'支付方式' not in dic or dic[u'支付方式'] is None:
            return json_response({'state':'failed','message':'lack of paystyle'})
        if  u'项目' not in dic or dic[u'项目'] is None:
            return json_response({'state':'failed','message':'lack of item'})
        if u'品牌' not  in dic :
            return json_response({'state':'failed','message':'lack of brand'})

        # 获取签名图片
        file_obj = request.FILES.get('sign', None)
        if file_obj is None:
            return json_response({'state':'failed','message':'lack of sign'})




        # 判断 全款 预付款 是否为数字

        price = dic[u'全款']
        advance_pay = dic[u'预付款']

        if  not price.isdigit() or  not advance_pay.isdigit():
            return json_response({'state':'failed','message':'price and advancepay must be digit '})

        # print dic[u'订单号']

        today = datetime.datetime.now().strftime("%Y-%m-%d") #今天


        # 取出预约单
        order = Order.objects.get(orderID=dic[u'订单号'])


        status = Status.objects.get(name=u'已签约')

        brand = dic[u'品牌']
        if brand == u'云锦婚礼':
            brand = 'YJ'
        if brand == u'黄河京都婚礼部':
            brand = 'HH'
        if brand == u'心情婚礼':
            brand = 'XQ'
        if brand == u'顶尖婚礼':
            brand = 'DJ'
        if brand == u'幸福港湾':
            brand = 'XF'
        if brand == u'大禾时代':
            brand = 'DH'
        if brand == u'小城故事':
            brand = 'XC'
        if brand == u'Ido':
            brand = 'ID'
        if brand == u'罗曼维庭':
            brand = 'LM'



        orderid = order.orderID[:2]+brand+order.orderID[2:]

        # 保存签名图片
        site_root = os.path.join(os.path.abspath(os.path.dirname(__file__)),'..')
        file_name = site_root+'/static/sign/'+orderid+'.png'
        # print os.path.abspath(file_name)
        f = open(file_name, 'w')
        print f
        for chunk in file_obj.chunks():
            f.write(chunk)
        f.close()


        order.orderID = orderid
        order.status = status
        order.signTime = today
        order.price = price
        advance_pay_old = order.advancePay
        order.advancePay = int(advance_pay) +advance_pay_old
        order.signImage = 'http://218.126.170.216:8000/'+file_name

        if u'备注' in dic:
            order.note = dic[u'备注']


        # 保存订单
        order.save()


        items = dic[u'项目']
        items_list = items.split('.')


        for one in items_list:
            if one is None:
                continue
            item = Item(name=one,order=order)
            item.save()

        # 删除旧订单
        order_old = Order.objects.filter(orderID=dic[u'订单号'])
        print order_old
        if order_old is not None:
            order_old.delete()

        return json_response({'state':'success',
                              'orderid':orderid,
                              'price':price,
                              'advancepay':advance_pay})
    elif request.method == 'OPTIONS':
        return json_response({})
    else:
        return json_response({
                                 'error': 'Invalid Method'
                             }, status=405)

# 销售人员
@csrf_exempt
@token_required
def sales(request):
    print 'xxx'
    if request.method == 'POST':

        salesman = SaleMan.objects.filter(user=request.token.user)
        print salesman
        man = []
        for one in salesman:
            dic = {}
            dic["name"] = one.name
            dic["jobNumber"] = one.jobNumber
            man.append(dic)

        manJSON = {"saleman": man}

        return json_response(manJSON)

    elif request.method == 'OPTIONS':
        return json_response({})
    else:
        return json_response({
                                 'error': 'Invalid Method'
                             }, status=405)

# 获取订单列表
@csrf_exempt
@token_required
def order(request):
    if request.method == 'POST':
        dic =  request.REQUEST
        response_dic = {}
        response_dic[u'state'] = u'failed'
        # 订单状态
        if u'status' not  in dic:
            response_dic[u'message'] = u'lack of status'
            return json_response(response_dic)
        if u'current_page' not in dic or not dic[u'current_page'].isdigit():
            response_dic[u'message'] = u'error currentPage'
            return json_response(response_dic)
        if u'num_per_page' not in dic or not dic[u'num_per_page'].isdigit():
            response_dic[u'message'] = u'error num_perpage'
            return json_response(response_dic)

        current_page = dic[u'current_page']
        num_per_page = dic[u'num_per_page']

        print  current_page

        status = Status.objects.get(name = dic[u'status'])
        print status
        sales = SaleMan.objects.filter(user=request.token.user)
        orderlist = []

        # 按联系人搜索订单

        if u'name' in dic and dic[u'name'] is not None:
            clients = Client.objects.filter(name=dic[u'name'])
            if 0==len(clients):
                response_dic[u'state'] = u'failed'
                response_dic[u'message'] = u'无此联系人信息'
                return json_response(response_dic)
            for client in clients:
                for sale in sales:
                    orders = Order.objects.filter(status=status,client=client,saleman=sale)
                    for one in orders:
                        if one is not None:
                            dic = {"orderID":one.orderID,"联系人":one.client.name,"负责人":one.saleman.name}
                            orderlist.append(dic)

        # 搜索该账户下所有指定状态订单
        else:
            for sale in sales:
                orders = Order.objects.filter(status=status,saleman=sale)
                for one in orders:
                    if one is not None:
                        dic = {"orderID":one.orderID,"联系人":one.client.name,"负责人":one.saleman.name}
                        orderlist.append(dic)

        # print orderlist
        paginator = Paginator(orderlist,num_per_page)


        if int(current_page) > paginator.num_pages or int(current_page)<1:
            response_dic[u'message'] = u'current_page out of range'
            return json_response(response_dic)

        list_current_page =  paginator.page(1).object_list
        print list_current_page
        response_dic = {'订单':list_current_page,
                        'num_pages':paginator.num_pages,
                        'state':'success'}


        return json_response(response_dic)
    elif request.method == 'OPTIONS':
        return json_response({})
    else:
        return json_response({
                                 'error': 'Invalid Method'
                             }, status=405)



# 品牌
@csrf_exempt
@token_required
def brand(request):
    if request.method == 'POST':
        brands = Brand.objects.all()
        print brands
        brand_list = []
        for one in  brands:
            brand_list.append(one.name)
        dic = {'品牌':brand_list}


        return json_response(dic)
    elif request.method == 'OPTIONS':
        return json_response({})
    else:
        return json_response({
                                 'error': 'Invalid Method'
                             }, status=405)

# 订单详情
@csrf_exempt
@token_required
def detail(request):
    dic = request.REQUEST

    if u'orderid' not in dic:
        return json_response({'state':'failed',
                              'message':'lack of orderid'})
    orderid = dic[u'orderid']
    order = Order.objects.get(orderID = orderid)

    client = order.client
    sale = order.saleman
    status = order.status

    if order is None:
        return json_response({'state':'failed',
                              'message':'no this order'})

    order_dic = model_to_dict(order)
    client_dic = model_to_dict(client)
    sale_dic = model_to_dict(sale)
    status_dic = model_to_dict(status)

    order_dic['client'] = client_dic
    order_dic['saleman'] = sale_dic
    order_dic['status'] = status_dic['name']
    if 'signTime'in order_dic and order_dic['signTime'] is not  None:
        sign_time = (order_dic['signTime']).strftime("%Y-%m-%d")
        order_dic['signTime'] = sign_time

    order_dic['party_nature'] = order.party_nature.name


    if 'orderTime' in order_dic and order_dic['orderTime'] is not None:
        order_time = (order_dic['orderTime']).strftime("%Y-%m-%d")
        order_dic['orderTime'] = order_time


    if 'weddingTime' in order_dic and order_dic['weddingTime'] is not None:
        wedding_time = (order_dic['weddingTime']).strftime("%Y-%m-%d")
        order_dic['weddingTime'] = wedding_time


    if 'answerDoorTime' in order_dic and order_dic['answerDoorTime'] is not None:
        answerDoor_time = (order_dic['answerDoorTime']).strftime("%Y-%m-%d")
        order_dic['answerDoorTime'] = answerDoor_time


    item_list = Item.objects.filter(order = order)

    item_response = []
    for item in item_list:
        item_response.append(item.name)

    response_dic = {}
    response_dic['state'] = 'success'
    response_dic['info'] = order_dic
    response_dic['items'] = item_response
    print order_dic

    return json_response(response_dic)

